<template>
  <el-dialog title="新建图形文件" :visible.sync="dialogVisible">
    <el-form :model="form" :rules="formRules" ref="ruleForm">
      <el-form-item label="文件名称" :label-width="formLabelWidth" prop="name">
        <el-input v-model="form.name" autocomplete="off"></el-input>
      </el-form-item>
      <!-- <el-form-item label="文件类型" :label-width="formLabelWidth" prop="type">
        <el-select v-model="form.type" placeholder="请选择文件类型">
          <el-option v-for="item of fileTypes" :key="item.type" 
            :label="item.title" :value="item.type"></el-option>
        </el-select>
      </el-form-item> -->
      <el-form-item label="文件别名" :label-width="formLabelWidth" prop="aliasName">
        <el-input v-model="form.aliasName" autocomplete="off"></el-input>
      </el-form-item>
    </el-form>
    <div slot="footer">
      <el-button @click="dialogVisible = false">取 消</el-button>
      <el-button type="primary" @click="handleClick">确 定</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { existGraphFile } from '@/api/draw.js'
import ConfigUtil from '@/utils/graph-utils/configUtil.js'

export default {
  name: 'NewGraphFileDialog',
  data() {
    var validateName = (rule, value, callback) => {
      if (value === '') {
        return callback(new Error('图形文件名称不允许为空'))
      }
      existGraphFile(value).then(response => {
        if (response.data) {
          return callback(new Error('图形文件已存在'))
        }
        callback()
      })
    }

    return {
      dialogVisible: false,

      form: {
        name: '',
        type: '1',
        aliasName: ''
      },
      formRules: {
        name: [
          { required: true, validator: validateName, trigger: 'blur' }
        ],
        type: [
          { required: true, message: '请选择文件类型', trigger: 'change' }
        ]
      },
      formLabelWidth: '120px'
    }
  },
  computed: {
    fileTypes: function() {
      return ConfigUtil.getGraphFileTypes()
    }
  },
  methods: {
    showDialog() {
      this.form = {
        name: '',
        type: '1',
        aliasName: ''
      }
      this.dialogVisible = true
    },

    handleClick() {
      const self = this
      self.$refs['ruleForm'].validate((valid) => {
        if (valid) {
          const graphFile = {
            name: self.form.name,
            type: self.form.type,
            aliasName: self.form.aliasName
          }
          self.$emit('submit', graphFile)
          self.dialogVisible = false
        } else {
          return false
        }
      })
    }
  }
}
</script>